#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- Data Handler
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/1/14 13:59
# Email lmay@lmaye.com
# ----------------------------------------------------------
import hashlib

import requests

from constant.sys_enum import SysEnum
from core import LOG
from utils import jdbc_util, rsa_utils
from utils.read_config import read_yml


def sync_account():
    """
    同步各客户端账号

    :return:
    """
    # 加载yml配置
    db_yml = read_yml(SysEnum.DB_PATH.value)
    connect = jdbc_util.sql_connect(db_yml["db"])
    client = db_yml["client"]
    # 执行SQL
    sql = """
        # select user_id, login_name, user_name, password, email, phonenumber, sex from sys_user
        select id, username, name, password, email, mobile, sex from sys_user
    """
    data = jdbc_util.sql_execute(sql, "select", connect=connect)
    url = 'http://127.0.0.1:9088/user/register'
    for it in data:
        # params = {
        #     "clientId": client["clientId"],
        #     "mobile": it["phonenumber"],
        #     "email": it["email"],
        #     # RSA加密, 其他客户端需hashlib.md5(b"123456").hexdigest(), 再进行RSA
        #     "password": rsa_utils.encrypt(it["password"]),
        #     "realName": it["user_name"],
        #     "sex": it["sex"],
        #     "userName": it["login_name"]
        # }
        params = {
            "clientId": client["clientId"],
            "mobile": it["mobile"],
            "email": it["email"],
            # RSA加密, 其他客户端需hashlib.md5(b"123456").hexdigest(), 再进行RSA
            "password": rsa_utils.encrypt(hashlib.md5(b"111111").hexdigest()),
            "realName": it["name"],
            "sex": it["sex"],
            "userName": it["username"]
        }
        # 设置请求头
        headers = {"content-type": "application/json", "Authorization": "None"}
        rs = requests.post(url, json=params, headers=headers)
        json = rs.json()
        LOG.info("响应结果: {}".format(json))
        if 200 == json["code"]:
            # 绑定sso id
            # jdbc_util.sql_execute("update sys_user set sso_id = %s where user_id = %s", "onlyOne", connect=connect,
            #                       args=(json["data"]["id"], it["user_id"]))
            jdbc_util.sql_execute("update sys_user set sso_id = %s where id = %s", "onlyOne", connect=connect,
                                  args=(json["data"]["id"], it["id"]))
